package com.paas.form.visualdev.controller;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.gencode.CodeFileType;
import com.gencode.entity.DevGenTemplateEntity;
import com.gencode.exception.GenCodeException;
import com.gencode.model.RequestParam;
import com.gencode.model.TableContext;
import com.gencode.rest.feign.service.DevGenCodeBuildService;
import com.gencode.rest.feign.service.DevGenTemplateService;
import com.gencode.util.CodeBuildNew;
import com.gencode.util.FileUtil;
import com.gencode.vo.VisualBuildFileVo;
import com.paas.common.jdbc.JdbcMeta;
import com.paas.common.jdbc.model.DbConfig;
import com.paas.common.jdbc.model.DbTableVo;
import com.paas.common.model.DataBaseEntity;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.annotion.Encrypt;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;
import com.paas.form.core.button.Button;
import com.paas.form.core.button.impl.DefultButton;
import com.paas.form.core.element.base.Form;
import com.paas.form.core.element.base.Search;
import com.paas.form.core.element.base.Table;
import com.paas.form.core.element.base.Tree;
import com.paas.form.core.element.constants.ServiceConstant;
import com.paas.form.core.element.constants.TableConstant;
import com.paas.form.core.element.field.*;
import com.paas.form.core.element.jsContent.ScriptContent;
import com.paas.form.visualdev.FormVisualdevEntity;
import com.paas.form.visualdev.service.IFormVisualdevService;
import com.paas.form.visualdev.util.*;
import com.publics.entity.UcResourcesDirEntity;
import com.publics.feign.service.IUcDataBaseService;
import com.publics.feign.service.IUcResourcesDirService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/form/formVisualdev")
@Api(description = "可视开发", tags = "")
public class FormVisualdevController extends BaseController {

    @Autowired
    public IUcDataBaseService ucDataBaseService;

    @Autowired
    public IFormVisualdevService formVisualdevService;

    @Autowired
    DevGenCodeBuildService devGenCodeBuildService;

    @Autowired
    public DevGenTemplateService devGenTemplateService;

    @Autowired
    public IUcResourcesDirService ucResourcesDirService;

    /**
     * 描述:获取编码的根目录
     *
     * @return
     */
    protected static String getCodeRootDir() {
        return System.getProperty("java.io.tmpdir") + File.separator + System.currentTimeMillis();
    }



    @RequestMapping(value = "/downloadCode")
    @ResponseBody
    @ApiOperation(value = "下载代码", notes = "下载代码")
    public void downloadCodeTest(@RequestBody FormVisualdevEntity formVisualbean , HttpServletResponse response) throws Exception {
        if (StringUtil.isNotEmpty(formVisualbean.getId())) {
            FormVisualdevEntity bean = formVisualdevService.getById(formVisualbean.getId());
            if (BeanUtil.isNotEmpty(bean)) {
                //暂时给定值
                String savePath = "com/paas/form";
                //模块名给定
//                String module = "dev";
                String module = bean.getEnCode();
                //默认字段配置
                FieLdsModel defaultField= new FieLdsModel();
                Config defConfig = new Config();
                defConfig.setPfKey("comInput");
                defaultField.setConfig(defConfig);


                JSONObject formjsobj = JSONObject.parseObject(bean.getFormData());
                FormDataModel formDataModel = JSONObject.parseObject(bean.getFormData(),FormDataModel.class);
                JSONArray fiedldsJsarray= JSONArray.parseArray(formDataModel.getFields());
                List<FieLdsModel> formFields = new ArrayList<>();
                for (int i = 0; i <fiedldsJsarray.size() ; i++) {
                    JSONObject fieldJson = fiedldsJsarray.getJSONObject(i);
                    Map<String,Object> fieldNewMap = new HashMap();
                    Set<String> keys = fieldJson.keySet();
                    for (String key:keys) {
                        String newkey = key.replaceAll("-","");
                        fieldNewMap.put(newkey,fieldJson.get(key));
                    }
                    FieLdsModel fieldsModel = JSONObject.parseObject(JSONObject.toJSONString(fieldNewMap), FieLdsModel.class);
                    if(fiedldsJsarray.getJSONObject(i).get("vModel") != null){
                        fieldsModel.setVModel((String) fiedldsJsarray.getJSONObject(i).get("vModel"));
                    }
                    formFields.add(fieldsModel);
                }

                ColumnDataModel columnData = JSONObject.parseObject(bean.getColumnData(),ColumnDataModel.class);
//                JSONArray searchfiedldsJsarray= JSONArray.parseArray(columnData.getSearchList());
//                List<SearchListModel> searchfields = new ArrayList<>();
                List<SearchListModel> searchfields = columnData.getSearchList();
                for (SearchListModel searchField: searchfields) {
                    boolean noSearchFormfield = true;
                    for (FieLdsModel formField:formFields) {
                        if(searchField.getColumnHumpName().equals(formField.getVModel())){
                            BeanUtil.copyProperties(searchField,formField);
                            noSearchFormfield = false;
                        }
                    }
                    if(noSearchFormfield){
                        BeanUtil.copyProperties(searchField,defaultField);
                        Config searConfig = new Config();
                        searConfig.setPfKey("comInput");
                        searConfig.setLabel(searchField.getRemarks());
                        searchField.setConfig(searConfig);
                        searchField.setVModel(searchField.getColumnHumpName());
                    }
                }

//                for (int i = 0; i <searchfiedldsJsarray.size() ; i++) {
//                    SearchListModel searchListModel = JSONObject.parseObject(String.valueOf(searchfiedldsJsarray.getJSONObject(i)), SearchListModel.class);
//                    if(searchfiedldsJsarray.getJSONObject(i).get("vModel") != null){
//                        searchListModel.setVModel((String) searchfiedldsJsarray.getJSONObject(i).get("vModel"));
//                    }
//                    searchfields.add(searchListModel);
//                }
//                List<SearchListModel> searchfields = searchfiedldsJsarray.toList(SearchListModel.class);

                List<Button> buttonList = new ArrayList<>();
                JSONArray btnsListfiedldsJsarray= JSONArray.parseArray(columnData.getBtnsList());
                if(BeanUtil.isNotEmpty(btnsListfiedldsJsarray)){
                    List<DefultButton> list = btnsListfiedldsJsarray.toList(DefultButton.class);
                    buttonList.addAll(list);
                }
                JSONArray columnBtnsListJsarray= JSONArray.parseArray(columnData.getColumnBtnsList());
                if(BeanUtil.isNotEmpty(columnBtnsListJsarray)){
                    List<DefultButton> columnBtnslist = columnBtnsListJsarray.toList(DefultButton.class);
                    buttonList.addAll(columnBtnslist);
                }
                ArrayList<ColumnListModel> tableFiedlds = (ArrayList<ColumnListModel>) columnData.getColumnList();
                for (ColumnListModel tableField: tableFiedlds) {
                    Boolean noFormField = true;
                    for (FieLdsModel formField:formFields) {
                        if(tableField.getColumnHumpName().equals(formField.getVModel())){
                            BeanUtil.copyProperties(tableField,formField);
                            noFormField = false;
                        }
                    }
                    if(noFormField){
                        BeanUtil.copyProperties(tableField,defaultField);
                        Config tabConfig = new Config();
                        tabConfig.setPfKey("comInput");
                        tabConfig.setLabel(tableField.getRemarks());
                        tableField.setConfig(tabConfig);
                        tableField.setVModel(tableField.getColumnHumpName());
                    }
                }

//                JSONArray fiedldsJsarray= JSONArray.parseArray(columnData.getColumnList());
//                List<TableField> fiedlds = new ArrayList<>();
//                for (int i = 0; i <fiedldsJsarray.size() ; i++) {
//                    TableField fiedld = JSONObject.parseObject(String.valueOf(fiedldsJsarray.getJSONObject(i)),TableField.class);
//                    if(fiedldsJsarray.getJSONObject(i).get("vModel") != null){
//                        fiedld.setVModel((String) fiedldsJsarray.getJSONObject(i).get("vModel"));
//                    }
//                    fiedlds.add(fiedld);
//                }
                //如果表单中存在配置，取用表单中的配置

                Map<String, Object> map = new HashMap<>();
                Map<String, Object> configMap = new HashMap<>();

                //主表名，同时也用于代码文件命名
                String masterTable=null;
//                DbTableVo dbTableVo = null;
                JSONArray tableJsonArray  = JSONArray.parseArray(bean.getTemTable());
                if(BeanUtil.isNotEmpty(tableJsonArray)){
                    for (int i = 0; i <tableJsonArray.size() ; i++) {
                        JSONObject item = (JSONObject) tableJsonArray.get(i);
                        if(item.get("typeId").equals(1)){
                            masterTable = item.get("tableName").toString();
//                            dbTableVo = JSONObject.parseObject(String.valueOf(item),DbTableVo.class);
                        }
                    }
                }
//                TableContext tableContext = VisualCodeCreate.parse(dbTableVo);

                //后端代码参数
                if(StringUtil.isEmpty(bean.getDbLinkId())){
//                    return RestResponse.error("数据源DbLinkId为空");
                    throw new Exception("数据源DbLinkId为空");
                }

                DataBaseEntity dataBaseEntity = ucDataBaseService.queryJdbcById(bean.getDbLinkId());
                DbConfig dbConfig = new DbConfig();
                dbConfig.setDriver(dataBaseEntity.getJdbcDrivers());
                dbConfig.setJdbcUrl(dataBaseEntity.getJdbcUrl());
                dbConfig.setUserName(dataBaseEntity.getJdbcUser());
                dbConfig.setPassword(dataBaseEntity.getJdbcPassword());
                dbConfig.setDbName(dataBaseEntity.getDbName());

                JdbcMeta jdbcMeta = null;
                DbTableVo dbTableVo = null;
                jdbcMeta = new JdbcMeta(dbConfig);
                dbTableVo = jdbcMeta.getTableWithColumn(dbConfig.getDbName(), masterTable);

                TableContext tableContext = VisualCodeCreate.parse(dbTableVo);

                map.put("module",module);
//                map.put("module",bean.getEnCode());
                map.put("moduleName",bean.getFullName());
                map.put("tableName",tableContext.getTableName());
                map.put("tableHumpName",tableContext.getTableHumpName());
                map.put("tableHumpUpper",tableContext.getTableHumpUpper());
                map.put("tableRemark",tableContext.getRemark());
                map.put("columns",tableContext.getColumns());
                map.put("superColumns",tableContext.getSuperColumns());


                //前端代码

                List<ScriptContent> jsList = new ArrayList<>();
                configMap.put("treeTitle",columnData.getTreeTitle());
                configMap.put("treeRelation",columnData.getTreeRelation());
                configMap.put("treeLazyType",columnData.getTreeLazyType());
                configMap.put("treePropsValue",columnData.getTreePropsValue());
                configMap.put("treePropsChildren",columnData.getTreePropsChildren());
                configMap.put("treePropsLabel",columnData.getTreePropsLabel());
                configMap.put("treeDataSource",columnData.getTreeDataSource());
                configMap.put("treeDictionary",columnData.getTreeDictionary());
                configMap.put("className",tableContext.getTableHumpName());
                configMap.put("formDataModel",formDataModel);
                configMap.put("classNameUtU",tableContext.getTableHumpUpper());
                configMap.put("module",module);

                String rightStyleStr = " style=\"width: 100%\"";

                //树形部分判断有无
                if(columnData.getType().equals(2)){
                    Tree tree = new Tree(configMap);
                    map.put("treeVue",tree.makeVue());
                    ScriptContent treeJS = tree.makeJs();
                    jsList.add(treeJS);
                    map.put("rightStyle"," ");
                }else {
                    map.put("treeVue","");
                    map.put("rightStyle",rightStyleStr);
                }

//                List<TableField> fiedlds = fiedldsJsarray.toList(TableField.class);

                Search search = new Search(bean.getFullName(),buttonList,searchfields);

                Table table = new Table(configMap,buttonList,tableFiedlds);

                map.put("searchVue",search.makeVue());
                map.put("tableVue",table.makeVue());

                ScriptContent searchJs = search.makeJs();
                jsList.add(searchJs);
                ScriptContent tableJs = table.makeJs();
                jsList.add(tableJs);


                String jsImportStr = "";
                String jsDataStr = "";
                String jsMethodsStr = "";
                String jsComponents = " GenFormInput,";
                String jsProps = "";

                for (ScriptContent itemJs :jsList) {
                    if(BeanUtil.isNotEmpty(itemJs)){
                        //拼接imports部分
                        if(StringUtil.isNotEmpty(itemJs.getImports())){
                            jsImportStr = jsImportStr + "\n" + itemJs.getImports();
                        }
                        //拼接Data部分
                        if(StringUtil.isNotEmpty(itemJs.getData())){
                            jsDataStr = jsDataStr + "\n" + itemJs.getData();
                        }
                        //拼接Methods部分
                        if(StringUtil.isNotEmpty(itemJs.getMethods())){
                            jsMethodsStr = jsMethodsStr + "\n" + itemJs.getMethods();
                        }
                    }
                }

                map.put("jsImport",jsImportStr);
                map.put("jsData",jsDataStr);
                map.put("jsMethods",jsMethodsStr);
                map.put("jsComponents",jsComponents);
//                map.put("jsProps",jsProps);
                String CodeContent = CodeBuildNew.getCodeString(map, TableConstant.vuePage);
                Map<String,String> vueCodeContentMap = new HashMap<>();
                vueCodeContentMap.put("index.vue",CodeContent);
                //表单文件
                Form formVue = new Form();
                String formCodeContent = formVue.getFormHtml(formDataModel,configMap);
                vueCodeContentMap.put("form.vue",formCodeContent);
                //service文件
                String serviceContent = CodeBuildNew.getCodeString(configMap, ServiceConstant.VM_SERVICE);
                String serviceFileName = configMap.get("classNameUtU").toString() + "Service.js";
                vueCodeContentMap.put(serviceFileName,serviceContent);

                //后端文件写入
                VisualBuildFileVo visualBuildFileVo = new VisualBuildFileVo();
                //暂默认使用第三套模板
                visualBuildFileVo.setWebType(3);
                List<DevGenTemplateEntity> tempList = devGenCodeBuildService.getTemplates(visualBuildFileVo);
                if(BeanUtil.isNotEmpty(tempList) && tempList.size() > 0){
                    //将代码模板写入文件
                    CodeFileType fileType= null;
                    String codeRootDir = VisualCodeCreate.getCodeRootDir();
                    try{
                        for (DevGenTemplateEntity genTempBean:tempList) {
                            //获取fileType 对象
                            String suffix = genTempBean.getSuffix();
                            fileType = new CodeFileType(suffix,tableContext.getTableHumpName());
                            String javaPackage = null;
                            String rootPackage = null;
                            if(!"htmlIndex".equals(suffix)){
                                javaPackage = fileType.getJavaPackage(savePath);
                                rootPackage = fileType.getPackage(savePath);
                            }
                            map.put("package",rootPackage);
                            map.put("javaPackage",javaPackage);
                            DevGenTemplateEntity newGenTempBean = CodeBuildNew.visualBuildContent(map,genTempBean);

                            //获取文件并编写文件信息
                            String fileDir = fileType.getFileDir(savePath,module);
                            String fileDirPath = codeRootDir+File.separator+fileDir;
                            String fileName = fileType.getFileName();
                            if("htmlIndex".equals(suffix)){
                                fileName = newGenTempBean.getFileName();
                            }
                            String filePath = fileDirPath+File.separator+fileName;
                            FileUtil.createFolder(fileDirPath);
                            FileUtil.write(newGenTempBean.getContent(), filePath);
                        }
                        //前端文件写入
                        CodeFileType vueFileType = new CodeFileType("htmlIndex",tableContext.getTableHumpName());
                        String vueFileDir = vueFileType.getFileDir(savePath,module);
                        String vueFileDirPath = codeRootDir+File.separator+vueFileDir;
                        for(Map.Entry<String, String> entry:vueCodeContentMap.entrySet()){
                            String vueFileName = entry.getKey();
                            String vueFilePath = vueFileDirPath+File.separator+vueFileName;
                            if(vueFileName.equals(serviceFileName)){
                                String serviceVueFileDirPath = codeRootDir+File.separator+module+"-html"+File.separator+ "src"+ File.separator+"service"+File.separator+"form";
                                String serviceVueFilePath = serviceVueFileDirPath+File.separator+vueFileName;
                                FileUtil.createFolder(serviceVueFileDirPath);
                                FileUtil.write(entry.getValue(), serviceVueFilePath);
                            }else {
                                FileUtil.createFolder(vueFileDirPath);
                                FileUtil.write(entry.getValue(), vueFilePath);
                            }

                        }

                        FileUtil.zip(codeRootDir, codeRootDir + ".zip");
                        File file = new File(codeRootDir + ".zip");
                        //流输出
                        ResponseFileUtil.writeFile(response, file);

                    } catch (Exception e) {
                        throw new GenCodeException("生成代码异常!", e);
                    } finally {
                        if (codeRootDir != null && !"".equals(codeRootDir)) {
                            FileUtil.deleteDir(new File(codeRootDir));
                        }
                    }
                }

            }
        } else {
            throw new Exception("参数id为空");
//            return RestResponse.error("参数id为空");
        }
//        return RestResponse.success();

    }


    @RequestMapping(value = "/previewCode", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "预览代码", notes = "预览代码")
    public RestResponse previewCode(String id, HttpServletResponse response) {
        if (StringUtil.isNotEmpty(id)) {
            FormVisualdevEntity bean = formVisualdevService.getById(id);
            if (BeanUtil.isNotEmpty(bean)) {
                //暂时给定值
                String savePath = "com/paas/form";
                //模块名给定
//                String module = "dev";
                String module = bean.getEnCode();
                //默认字段配置
                FieLdsModel defaultField= new FieLdsModel();
                Config defConfig = new Config();
                defConfig.setPfKey("comInput");
                defaultField.setConfig(defConfig);


                JSONObject formjsobj = JSONObject.parseObject(bean.getFormData());
                FormDataModel formDataModel = JSONObject.parseObject(bean.getFormData(),FormDataModel.class);
                JSONArray fiedldsJsarray= JSONArray.parseArray(formDataModel.getFields());
                List<FieLdsModel> formFields = new ArrayList<>();
                for (int i = 0; i <fiedldsJsarray.size() ; i++) {
                    JSONObject fieldJson = fiedldsJsarray.getJSONObject(i);
                    Map<String,Object> fieldNewMap = new HashMap();
                    Set<String> keys = fieldJson.keySet();
                    for (String key:keys) {
                        String newkey = key.replaceAll("-","");
                        fieldNewMap.put(newkey,fieldJson.get(key));
                    }
                    FieLdsModel fieldsModel = JSONObject.parseObject(JSONObject.toJSONString(fieldNewMap), FieLdsModel.class);
                    if(fiedldsJsarray.getJSONObject(i).get("vModel") != null){
                        fieldsModel.setVModel((String) fiedldsJsarray.getJSONObject(i).get("vModel"));
                    }
                    formFields.add(fieldsModel);
                }

                ColumnDataModel columnData = JSONObject.parseObject(bean.getColumnData(),ColumnDataModel.class);
                List<SearchListModel> searchfields = columnData.getSearchList();
                for (SearchListModel searchField: searchfields) {
                    boolean noSearchFormfield = true;
                    for (FieLdsModel formField:formFields) {
                        if(searchField.getColumnHumpName().equals(formField.getVModel())){
                            BeanUtil.copyProperties(searchField,formField);
                            noSearchFormfield = false;
                        }
                    }
                    if(noSearchFormfield){
                        BeanUtil.copyProperties(searchField,defaultField);
                        Config searConfig = new Config();
                        searConfig.setPfKey("comInput");
                        searConfig.setLabel(searchField.getRemarks());
                        searchField.setConfig(searConfig);
                        searchField.setVModel(searchField.getColumnHumpName());
                    }
                }


                List<Button> buttonList = new ArrayList<>();
                JSONArray btnsListfiedldsJsarray= JSONArray.parseArray(columnData.getBtnsList());
                if(BeanUtil.isNotEmpty(btnsListfiedldsJsarray)){
                    List<DefultButton> list = btnsListfiedldsJsarray.toList(DefultButton.class);
                    buttonList.addAll(list);
                }
                JSONArray columnBtnsListJsarray= JSONArray.parseArray(columnData.getColumnBtnsList());
                if(BeanUtil.isNotEmpty(columnBtnsListJsarray)){
                    List<DefultButton> columnBtnslist = columnBtnsListJsarray.toList(DefultButton.class);
                    buttonList.addAll(columnBtnslist);
                }
                ArrayList<ColumnListModel> tableFiedlds = (ArrayList<ColumnListModel>) columnData.getColumnList();
                for (ColumnListModel tableField: tableFiedlds) {
                    Boolean noFormField = true;
                    for (FieLdsModel formField:formFields) {
                        if(tableField.getColumnHumpName().equals(formField.getVModel())){
                            BeanUtil.copyProperties(tableField,formField);
                            noFormField = false;
                        }
                    }
                    if(noFormField){
                        BeanUtil.copyProperties(tableField,defaultField);
                        Config tabConfig = new Config();
                        tabConfig.setPfKey("comInput");
                        tabConfig.setLabel(tableField.getRemarks());
                        tableField.setConfig(tabConfig);
                        tableField.setVModel(tableField.getColumnHumpName());
                    }
                }
                //如果表单中存在配置，取用表单中的配置

                Map<String, Object> map = new HashMap<>();
                Map<String, Object> configMap = new HashMap<>();

                //主表名，同时也用于代码文件命名
                String masterTable=null;
//                DbTableVo dbTableVo = null;
                JSONArray tableJsonArray  = JSONArray.parseArray(bean.getTemTable());
                if(BeanUtil.isNotEmpty(tableJsonArray)){
                    for (int i = 0; i <tableJsonArray.size() ; i++) {
                        JSONObject item = (JSONObject) tableJsonArray.get(i);
                        if(item.get("typeId").equals(1)){
                            masterTable = item.get("tableName").toString();
//                            dbTableVo = JSONObject.parseObject(String.valueOf(item),DbTableVo.class);
                        }
                    }
                }
//                TableContext tableContext = VisualCodeCreate.parse(dbTableVo);

                //后端代码参数
                if(StringUtil.isEmpty(bean.getDbLinkId())){
                    return RestResponse.error("数据源DbLinkId为空");
                }

                DataBaseEntity dataBaseEntity = ucDataBaseService.queryJdbcById(bean.getDbLinkId());
                DbConfig dbConfig = new DbConfig();
                dbConfig.setDriver(dataBaseEntity.getJdbcDrivers());
                dbConfig.setJdbcUrl(dataBaseEntity.getJdbcUrl());
                dbConfig.setUserName(dataBaseEntity.getJdbcUser());
                dbConfig.setPassword(dataBaseEntity.getJdbcPassword());
                dbConfig.setDbName(dataBaseEntity.getDbName());

                JdbcMeta jdbcMeta = null;
                DbTableVo dbTableVo = null;
                jdbcMeta = new JdbcMeta(dbConfig);
                dbTableVo = jdbcMeta.getTableWithColumn(dbConfig.getDbName(), masterTable);

                TableContext tableContext = VisualCodeCreate.parse(dbTableVo);

                map.put("module",module);
//                map.put("module",bean.getEnCode());
                map.put("moduleName",bean.getFullName());
                map.put("tableName",tableContext.getTableName());
                map.put("tableHumpName",tableContext.getTableHumpName());
                map.put("tableHumpUpper",tableContext.getTableHumpUpper());
                map.put("tableRemark",tableContext.getRemark());
                map.put("columns",tableContext.getColumns());
                map.put("superColumns",tableContext.getSuperColumns());


                //前端代码

                List<ScriptContent> jsList = new ArrayList<>();
                configMap.put("treeTitle",columnData.getTreeTitle());
                configMap.put("treeRelation",columnData.getTreeRelation());
                configMap.put("treeLazyType",columnData.getTreeLazyType());
                configMap.put("treePropsValue",columnData.getTreePropsValue());
                configMap.put("treePropsChildren",columnData.getTreePropsChildren());
                configMap.put("treePropsLabel",columnData.getTreePropsLabel());
                configMap.put("treeDataSource",columnData.getTreeDataSource());
                configMap.put("treeDictionary",columnData.getTreeDictionary());
                configMap.put("className",tableContext.getTableHumpName());
                configMap.put("formDataModel",formDataModel);
                configMap.put("classNameUtU",tableContext.getTableHumpUpper());
                configMap.put("module",module);

                String rightStyleStr = " style=\"width: 100%\"";

                //树形部分判断有无
                if(columnData.getType().equals(2)){
                    Tree tree = new Tree(configMap);
                    map.put("treeVue",tree.makeVue());
                    ScriptContent treeJS = tree.makeJs();
                    jsList.add(treeJS);
                    map.put("rightStyle"," ");
                }else {
                    map.put("treeVue","");
                    map.put("rightStyle",rightStyleStr);
                }

//                List<TableField> fiedlds = fiedldsJsarray.toList(TableField.class);

                Search search = new Search(bean.getFullName(),buttonList,searchfields);

                Table table = new Table(configMap,buttonList,tableFiedlds);

                map.put("searchVue",search.makeVue());
                map.put("tableVue",table.makeVue());

                ScriptContent searchJs = search.makeJs();
                jsList.add(searchJs);
                ScriptContent tableJs = table.makeJs();
                jsList.add(tableJs);


                String jsImportStr = "";
                String jsDataStr = "";
                String jsMethodsStr = "";
                String jsComponents = " GenFormInput,";
                String jsProps = "";

                for (ScriptContent itemJs :jsList) {
                    if(BeanUtil.isNotEmpty(itemJs)){
                        //拼接imports部分
                        if(StringUtil.isNotEmpty(itemJs.getImports())){
                            jsImportStr = jsImportStr + "\n" + itemJs.getImports();
                        }
                        //拼接Data部分
                        if(StringUtil.isNotEmpty(itemJs.getData())){
                            jsDataStr = jsDataStr + "\n" + itemJs.getData();
                        }
                        //拼接Methods部分
                        if(StringUtil.isNotEmpty(itemJs.getMethods())){
                            jsMethodsStr = jsMethodsStr + "\n" + itemJs.getMethods();
                        }
                    }
                }

                map.put("jsImport",jsImportStr);
                map.put("jsData",jsDataStr);
                map.put("jsMethods",jsMethodsStr);
                map.put("jsComponents",jsComponents);
//                map.put("jsProps",jsProps);
                String CodeContent = CodeBuildNew.getCodeString(map, TableConstant.vuePage);
                Map<String,String> vueCodeContentMap = new HashMap<>();
                vueCodeContentMap.put("index.vue",CodeContent);
                //表单文件
                Form formVue = new Form();
                String formCodeContent = formVue.getFormHtml(formDataModel,configMap);
                vueCodeContentMap.put("form.vue",formCodeContent);
                //service文件
                String serviceContent = CodeBuildNew.getCodeString(configMap, ServiceConstant.VM_SERVICE);
                String serviceFileName = configMap.get("classNameUtU").toString() + "Service.js";
                vueCodeContentMap.put(serviceFileName,serviceContent);

                //后端文件写入
                VisualBuildFileVo visualBuildFileVo = new VisualBuildFileVo();
                //暂默认使用第三套模板
                visualBuildFileVo.setWebType(3);
                List<DevGenTemplateEntity> tempList = devGenCodeBuildService.getTemplates(visualBuildFileVo);

                List<DevGenTemplateEntity> newTempList = new ArrayList<>();

                if(BeanUtil.isNotEmpty(tempList) && tempList.size() > 0){
                    //将代码模板写入文件
                    CodeFileType fileType= null;
                    String codeRootDir = VisualCodeCreate.getCodeRootDir();
                    try{
                        for (DevGenTemplateEntity genTempBean:tempList) {
                            //获取fileType 对象
                            String suffix = genTempBean.getSuffix();
                            fileType = new CodeFileType(suffix,tableContext.getTableHumpName());
                            String javaPackage = null;
                            String rootPackage = null;
                            if(!"htmlIndex".equals(suffix)){
                                javaPackage = fileType.getJavaPackage(savePath);
                                rootPackage = fileType.getPackage(savePath);
                            }
                            map.put("package",rootPackage);
                            map.put("javaPackage",javaPackage);
                            DevGenTemplateEntity newGenTempBean = CodeBuildNew.visualBuildContent(map,genTempBean);

                            //获取文件并编写文件信息
                            String fileDir = fileType.getFileDir(savePath,module);
                            String fileDirPath = codeRootDir+File.separator+fileDir;
                            String fileName = fileType.getFileName();
                            if("htmlIndex".equals(suffix)){
                                fileName = newGenTempBean.getFileName();
                            }
                            newTempList.add(newGenTempBean);
                        }
                        //前端文件写入
                        CodeFileType vueFileType = new CodeFileType("htmlIndex",tableContext.getTableHumpName());
                        String vueFileDir = vueFileType.getFileDir(savePath,module);
                        String vueFileDirPath = codeRootDir+File.separator+vueFileDir;
                        for(Map.Entry<String, String> entry:vueCodeContentMap.entrySet()){
                            String vueFileName = entry.getKey();
                            String vueFilePath = vueFileDirPath+File.separator+vueFileName;
                            DevGenTemplateEntity devGenTemplateHtmlBean = new DevGenTemplateEntity();
                            if(vueFileName.equals(serviceFileName)){
                                String serviceVueFileDirPath = codeRootDir+File.separator+module+"-html"+File.separator+ "src"+ File.separator+"service"+File.separator+"form";
                                String serviceVueFilePath = serviceVueFileDirPath+File.separator+vueFileName;
                                devGenTemplateHtmlBean.setSavePath(serviceVueFilePath);
                            }else {
                                devGenTemplateHtmlBean.setSavePath(vueFilePath);
                            }

//                            FileUtil.createFolder(vueFileDirPath);
//                            FileUtil.write(entry.getValue(), vueFilePath);

                            devGenTemplateHtmlBean.setContent(entry.getValue());
                            devGenTemplateHtmlBean.setFileName(entry.getKey());
                            devGenTemplateHtmlBean.setSuffix("htmlIndex");
                            newTempList.add(devGenTemplateHtmlBean);

                        }
                        return RestResponse.success().put("data",newTempList);

                    } catch (Exception e) {
                        throw new GenCodeException("生成代码异常!", e);
                    }
                }

            }
        } else {
            return RestResponse.error("参数id为空");
        }
        return RestResponse.error("获取预览代码出错");

    }



    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "-保存")
    public void save(@RequestBody FormVisualdevEntity formVisualdevEntity) throws ParseException {
        if (BeanUtil.isNotEmpty(formVisualdevEntity)) {
            injectUpdateDataAuth(formVisualdevEntity);
            formVisualdevEntity.setStatus(SystemConst.NORMAL_STATUS);
        }
        formVisualdevService.save(formVisualdevEntity);
    }

    @RequestMapping(value = "/saveBatch", method = RequestMethod.POST)
    @ApiOperation(value = "批量保存信息", notes = "批量保存信息")
    @OperLog(operType = OprLogConstant.UPDATE, operModul = "", operDescribe = "-批量保存修改")
    public void saveBatch(@RequestBody List<FormVisualdevEntity> list) throws ParseException {
        if (list != null && list.size() > 0) {
            injectUpdateDataAuth(list);
            for (FormVisualdevEntity formVisualdevEntity : list) {
                formVisualdevEntity.setStatus(SystemConst.NORMAL_STATUS);
            }
        }
        formVisualdevService.saveBatch(list);
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void deleteById(String id) {
        if (null != id && !"".equals(id)) {
            FormVisualdevEntity formVisualdevEntity = new FormVisualdevEntity();
            injectUpdateDataAuth(formVisualdevEntity);
            formVisualdevEntity.setId(id);
            formVisualdevEntity.setStatus(SystemConst.DELTE_STATUS);
            formVisualdevService.updateById(formVisualdevEntity);
//            formVisualdevService.deleteByEntity(formVisualdevEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormVisualdevEntity formVisualdevEntity = new FormVisualdevEntity();
            injectUpdateDataAuth(formVisualdevEntity);
            //formVisualdevService.deleteBatchIds(ids);

            List<FormVisualdevEntity> formVisualdevEntityList = formVisualdevService.getBatchByIds(ids);
            if (BeanUtil.isNotEmpty(formVisualdevEntityList) && formVisualdevEntityList.size() > 0) {
                for (FormVisualdevEntity formVisualdevBean : formVisualdevEntityList) {
                    formVisualdevBean.setStatus(SystemConst.DELTE_STATUS);
                }
            }
            formVisualdevService.updateBatchById(formVisualdevEntityList);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    @Encrypt
    @ResponseBody
    public FormVisualdevEntity queryById(String id) {
        FormVisualdevEntity bean = formVisualdevService.getById(id);
        return bean;
    }

    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    @Encrypt
    @ResponseBody
    public List queryBatchByIds(@RequestBody List<String> ids) {
        List list = formVisualdevService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    @ResponseBody
    @Encrypt
    public IPage queryPage(FormVisualdevEntity formVisualdevEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formVisualdevEntity);
        formVisualdevEntity.setStatus(SystemConst.NORMAL_STATUS);
        IPage<FormVisualdevEntity> pageBean = formVisualdevService.getPage(formVisualdevEntity, currentPage, pageSize);
        List<FormVisualdevEntity> list = pageBean.getRecords();
        List<String> resIdList = list.stream().map(FormVisualdevEntity::getResId).distinct().collect(Collectors.toList());
        //资源目录集合
        Map<String,String> showNameMap = new HashMap<>();
        for (String resId: resIdList) {
            UcResourcesDirEntity ucResourcesDirEntity = new UcResourcesDirEntity();
            ucResourcesDirEntity.setId(resId);
            UcResourcesDirEntity resourcesDirEntity = ucResourcesDirService.queryById(ucResourcesDirEntity);
            if(BeanUtil.isNotEmpty(resourcesDirEntity) && StringUtil.isNotEmpty(resourcesDirEntity.getShowName())){
                showNameMap.put(resId,resourcesDirEntity.getShowName());
            }
        }
        for (FormVisualdevEntity bean: list) {
            if(StringUtil.isNotEmpty(bean.getResId()) && StringUtil.isNotEmpty(showNameMap.get(bean.getResId()))){
                bean.setResShowName(showNameMap.get(bean.getResId()));

            }

        }
        pageBean.setRecords(list);
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    @Encrypt
    @ResponseBody
    public List queryList(FormVisualdevEntity formVisualdevEntity) {
        injectCheckDataAuth(formVisualdevEntity);
        formVisualdevEntity.setStatus(SystemConst.NORMAL_STATUS);
        List list = formVisualdevService.getList(formVisualdevEntity);
        return list;
    }

    /*
     * @Author lxb
     * @Description //TODO
     * @Date 17:22 2023/4/27
     * @Param
     * @return
     **/

    @RequestMapping(value = "/copyOne", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    @Encrypt
    @ResponseBody
    public RestResponse copyOne(String id) {
        FormVisualdevEntity bean = formVisualdevService.getById(id);
        if (BeanUtil.isNotEmpty(bean)) {
            FormVisualdevEntity newBean = new FormVisualdevEntity();
            BeanUtil.copyProperties(newBean, bean);
            newBean.setId(null);
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            newBean.setFullName(newBean.getFullName() + "copyOn:" + format.format(now));
            newBean.setCreateDate(null);
            newBean.setModifyDate(null);
            formVisualdevService.save(newBean);
            return RestResponse.success("复制成功");
        } else {
            RestResponse.error("不存在该条数据");

        }
        return RestResponse.error("复制出错");
    }




}